package com.cff.springbootwork.jpalock.service;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.cff.springbootwork.jpalock.dao.UserInfoDao;
import com.cff.springbootwork.jpalock.domain.UserInfo;

@Service
public class UserInfoService {
	@Autowired
	UserInfoDao userInfoDao;

	public UserInfo getUserInfoByUserName(String userName) {
		return userInfoDao.findById(userName).orElse(null);
	}

	public void save(UserInfo entity) {
		userInfoDao.save(entity);
	}

	public void updateWithTimeOptimistic(UserInfo entity, int time) throws InterruptedException {		
		UserInfo userInfo = userInfoDao.findById(entity.getUserName()).orElse(null);
		if (userInfo == null)
			return;

		if (!StringUtils.isEmpty(entity.getMobile())) {
			userInfo.setMobile(entity.getMobile());
		}
		if (!StringUtils.isEmpty(entity.getName())) {
			userInfo.setName(entity.getName());
		}
		Thread.sleep(time * 1000L);

		userInfoDao.save(userInfo);
	}

	public void delete(String userName) {
		userInfoDao.deleteById(userName);
	}

	public void updateOptimistic(UserInfo entity) {
		UserInfo userInfo = userInfoDao.findById(entity.getUserName()).orElse(null);
		if (userInfo == null)
			return;

		if (!StringUtils.isEmpty(entity.getMobile())) {
			userInfo.setMobile(entity.getMobile());
		}
		if (!StringUtils.isEmpty(entity.getName())) {
			userInfo.setName(entity.getName());
		}

		userInfoDao.save(userInfo);
	}

	@Transactional
	public UserInfo getUserInfoByUserNamePessimistic(String userName) {
		return userInfoDao.findByUserName(userName);
	}
	
	@Transactional
	public void updateWithTimePessimistic(UserInfo entity, int time) throws InterruptedException {		
		UserInfo userInfo = userInfoDao.findByUserName(entity.getUserName());
		if (userInfo == null)
			return;

		if (!StringUtils.isEmpty(entity.getMobile())) {
			userInfo.setMobile(entity.getMobile());
		}
		if (!StringUtils.isEmpty(entity.getName())) {
			userInfo.setName(entity.getName());
		}
		Thread.sleep(time * 1000L);

		userInfoDao.save(userInfo);
	}
	
	@Transactional
	public void updatePessimistic(UserInfo entity) {
		UserInfo userInfo = userInfoDao.findByUserName(entity.getUserName());
		if (userInfo == null)
			return;

		if (!StringUtils.isEmpty(entity.getMobile())) {
			userInfo.setMobile(entity.getMobile());
		}
		if (!StringUtils.isEmpty(entity.getName())) {
			userInfo.setName(entity.getName());
		}

		userInfoDao.save(userInfo);
	}
}
